package com.lby.psychology.controller;

import com.lby.psychology.model.ResponseData;
import com.lby.psychology.model.vo.PsycUploadVo;
import com.lby.psychology.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.script.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private TestService testService;

    public static void main(String[] args) throws InterruptedException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings(); //Local级别的Binding
        String script = "basicGrowth +  continuousGrowth*3"; //定义函数并调用
        CompiledScript JSFunction = null; //解析编译脚本函数
        try {
            JSFunction = compilable.compile(script);
            bindings.put("basicGrowth", 100);
            bindings.put("continuousGrowth", 50);
            Object result = JSFunction.eval(bindings);
            System.out.println(result); //调用缓存着的脚本函数对象，Bindings作为参数容器传入
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }



    @PostMapping(value = "/uploadFile",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseData<String> uploadFile(PsycUploadVo vo) throws IOException {

        String [] strings = vo.getRelativePath().split("/");

        if (strings.length > 1 ) {
            File file1 = new File("C:/Users/coding/Pictures/" + strings[0]);
            file1.mkdir();
        }

        FileOutputStream outputStream = new FileOutputStream("C:/Users/coding/Pictures/"+vo.getRelativePath());
        outputStream.write(vo.getFile().getBytes());


        outputStream.close();

        return new ResponseData<>(vo.getFile().getOriginalFilename());
    }

    @GetMapping("/testTransactional")
    public ResponseData<Void> testTransactional() {
        testService.testTransactional();
        return new ResponseData<>();
    }

}
